/*
 * rot13.c: ROT13 cipher test application
 *
 * Authors: Nora Tarano	ntarano@andrew.cmu.edu
 *          Yuan Meng	yuanm@andrew.cmu.edu
 *          Yipeng Yun	yipengy@andrew.cmu.edu
 * Date:    Sat Oct 15, 2011
 */

#include <unistd.h>
#include <stdlib.h>
#include <bits/fileno.h>
#include <errno.h>

#define BUFF_SIZE	128
#define SYSCALL_ERROR	1
#define EXIT_SUCCESS	0

#define NEWLINE 0xa
#define RETURN 0xd

int main(int argc, char *argv[]) {
	
	char str[BUFF_SIZE], currChar;
	int count, i;

	// output argvs to stdout
	/*int argLength;
	for (i = 0; i < argc; ++i) {
		if (argv[i] != 0x0) {
			for (argLength = 0; ; ++argLength) {
				if (argv[i][argLength] == 0x0 || argv[i][argLength] == ' ')
					break;
			}
			if (write(STDOUT_FILENO, argv[i], argLength + 1) < 0)
				exit(SYSCALL_ERROR);
		}
		else break;
	}*/
	
	while (1) {
		count = read(STDIN_FILENO, str, BUFF_SIZE);
		if (count < 0)
			exit(SYSCALL_ERROR); // exit on error
		if (str[0] == RETURN)
			exit(EXIT_SUCCESS); // exit on newline
		// apply Ceasar cipher
		for (i = 0; i < count; ++i) {
			currChar = str[i];
			if ((currChar >= 65 && currChar <= 77) ||
			     (currChar >= 97 && currChar <= 109))
				str[i] += 13;
			else if ((currChar >= 78 && currChar <= 90) ||
			     (currChar >= 110 && currChar <= 122))
				str[i] -= 13;
		}
		
		if (write(STDOUT_FILENO, str, count) < 0)
			exit(SYSCALL_ERROR);	// exit on error
	}
	exit(EXIT_SUCCESS);
	return EXIT_SUCCESS;
}
